<?php
// +----------------------------------------------------------------------
// | redis单例
// +----------------------------------------------------------------------
// | Author: AES <fancs_it@163.com>
// +----------------------------------------------------------------------

namespace app\common\lib;

class Predis
{
    protected static $_instance;
    protected $redis;

    public function __construct()
    {
        //连接redis
        try {
            $this->redis = new \Redis();
            $res = $this->redis->connect(config('redis.host'), config('redis.port'),config('redis.timeout'));
            if($res === false){
                throw new \Exception("Error Redis Connect", 1);
            }
        }catch (\Exception $e){
            return $e->getMessage().'<br/>';
        }
        
    }

    public static function getInstance()
    {
        
        if(!self::$_instance instanceof self){
            self::$_instance = new self;
        }
        return self::$_instance;
    }

    /**
     * redis set方法
     */
    public function set($key,$value,$time=0)
    {
        if(empty($key)) return '';

        is_array($value) && $value = json_encode($value);

        if(!$time){
            return $this->redis->set($key,$value);
        }else {
            return $this->redis->setex($key,$time,$value);
        }
    }
    /**
     * redis get方法
     */
    public function get($key)
    {
        if(empty($key)) return '';

        return $this->redis->get($key);
    }
}